home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1695 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.3 KB  |  64 lines

  1. Path: newshost.uni-koblenz.de!news
  2. From: Thomas Schweitzer <schweitz@informatik.uni-koblenz.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Problem: Virtual base class
  5. Date: 12 Jan 1996 09:52:11 GMT
  6. Organization: University of Koblenz, Germany
  7. Message-ID: <4d5b0b$m4b@newshost.uni-koblenz.de>
  8. NNTP-Posting-Host: grimm.uni-koblenz.de
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 1.1N (X11; I; SunOS 4.1.3 sun4m)
  13. X-URL: news:comp.lang.c++/138657-139657
  14.  
  15. Hi.
  16. I've got a problem concerning virtual base classes, multiple inheritance and
  17. casting. Consider the following class hierarchy:
  18.  
  19.          _____A_____
  20.         |     |     |
  21.         B  virtual  C
  22.         |     |     |
  23.         |_____|_____|
  24.               D
  25.  
  26. The problem: I can cast an instance of D to an instance of A. Having done this,
  27. the compiler forbids casting in the other direction. Now a little program:
  28.  
  29. class A {
  30.     int a;
  31. };
  32.  
  33. class B : virtual public A {
  34.     int b;
  35. };
  36.  
  37. class C : virtual public A {
  38.     int c;
  39. };
  40.  
  41. class D : virtual public A, public B, public C {
  42.     int d;
  43. };
  44.  
  45. void main ()
  46. {
  47.  
  48.     A* a;
  49.     D* d = new D,
  50.        anotherD;
  51.        
  52.     a = (A*) d;
  53.     anotherD = (D*) a; // Why? : cannot cast up from virtual baseclass `A'
  54.  
  55. }
  56.  
  57. Why is the casting in the last line not possible?
  58.  
  59. Please reply via e-mail.
  60.  
  61. Thanks in advance
  62. Thomas
  63.  
  64.